<html>
<head>
    <meta charset="UTF-8"></meta>
    <title>springboot项目WebSocket测试demo</title>
</head>
<body>
<h3>springboot项目websocket测试demo</h3>
<h4>测试说明</h4>
<h5>文本框中数据数据，点击‘发送测试’，文本框中的数据会发送到后台websocket，后台接受到之后，会再推送数据到前端，展示在下方；点击关闭连接，可以关闭该websocket；可以跟踪代码，了解具体的流程；代码上有详细注解</h5>
<br />
<input id="apiText" type="text" />
<button onclick="sendApiText()">api请求发送测试</button>
<hr />

<input id="text" type="text" />
<button onclick="send()">websocket发送测试</button>
<hr />
<button onclick="clos()">关闭连接</button>
<hr />
<div id="message"></div>
<script>
    var websocket = null;
    if('WebSocket' in window){
        var timestamp=new Date().getTime();
        var param = 1;
        websocket = new WebSocket("ws://127.0.0.1:8888/websocket/"+param);
    }else{
        alert("您的浏览器不支持websocket");
    }
    websocket.onerror = function(){
        setMessageInHtml("send error！");
    }
    websocket.onopen = function(){
        setMessageInHtml("connection success！")
    }
    websocket.onmessage  = function(event){
        setMessageInHtml(event.data);
    }
    websocket.onclose = function(){
        setMessageInHtml("closed websocket!")
    }
    window.onbeforeunload = function(){
        clos();
    }
    function setMessageInHtml(message){
        document.getElementById('message').innerHTML += "收到的消息:" + message + "<br/>" ;
    }
    function clos(){
        websocket.close(3000,"强制关闭");
    }
    function send(){
        var msg = document.getElementById('text').value;
        websocket.send(msg);
    }
    function sendApiText(){
        var msg = document.getElementById('apiText').value;
        var url = "http://127.0.0.1:8888/demo/notify/" + msg;

        var httpRequest = new XMLHttpRequest();//第一步：建立所需的对象
        httpRequest.open('GET', url, true);//第二步：打开连接  将请求参数写在url中  ps:"./Ptest.php?name=test&nameone=testone"
        httpRequest.send();//第三步：发送请求  将请求参数写在URL中
        /**
         * 获取数据后的处理程序
         */
        httpRequest.onreadystatechange = function () {
            if (httpRequest.readyState == 4 && httpRequest.status == 200) {
                var json = httpRequest.responseText;//获取到json字符串，还需解析
                console.log(json);
            }
        };
    }

</script>
</body>
</html>